<?php


namespace app\service\algorithm;


/**
 * author Sept
 * date 2021-05-19
 */
class CRC8{
    /**
     * HexToBytes 十六进制字符串转byte数组
     * @param $string
     * @return array
     */
    private function HexToBytes($string)
    {
        $bytes = array();
        for ($i = 0; $i < strlen($string) / 2; $i++)
            $bytes[$i] = hexdec($string[$i * 2] . $string[$i * 2 + 1]);
        return $bytes;
    }

    /**
     * BytesToHex byte数组转十六进制字符串
     * @param $bytes
     * @return string
     */
    private function BytesToHex($bytes)
    {
        $str = "";
        for ($i = 0; $i < count($bytes); $i++)
            $str .= sprintf("%02X", $bytes[$i]);
        return $str;
    }

    /**
     * byte数组计算CRC8
     * @param array $bytes
     * @param bool $len
     * @return int byte
     */
    public function crc8(array $bytes, $len = false)
    {
        if (!$len) $len = count($bytes);
        $crc = 0;

        for ($i = 0; $i < $len; $i++) {
            $crc = $crc ^ $bytes[$i];


            for ($n = 0; $n < 8; $n++) {
                if ($crc & 1) {
                    $crc = ($crc >> 1) ^ 0x8c;
                } else {
                    $crc >>= 1;
                }
            }
        }
        return $crc;
    }

    /**
     * 十六进制字符串计算CRC8
     * @param String $packet  需要计算CRC8的十六进制字符串
     * @param bool $isHex   计算CRC8后是否转十六进制
     * @return int|mixed|string  byte|HexString
     */
    public function HexToCRC8($packet,$isHex){
        $bytes=$this->HexTobytes($packet);
        $bytes_result[]=$this->crc8($bytes);
        if ($isHex) return $this->BytesToHex($bytes_result);

        return $bytes_result[0];

    }
}
